<template>
  <div class="plc bg-white page-content content full-height padding-l-20 padding-t-20 padding-r-20">
    <div class="flex full-width full-height">
      <div style="width: 340px; max-height: 100%" class="padding-r-20 flex column">
        <div class="flex items-center header">
          <div style="width: 40px">
            <q-btn
              style="font-size: 18px"
              flat
              round
              dense
              color="primary"
              class="iconfont icontubiao2-97"
              @click="setPoint"
            >
              <q-tooltip>设置</q-tooltip>
            </q-btn>
          </div>
          <div class="cell repName text-weight-bold">数据点
            <div class="cursor-pointer margin-l-10 inline-block" style="font-weight: normal">
              <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" style="margin-top: -3px"/>
              <q-tooltip max-width="300px">配置后才开始存储历史数据</q-tooltip>
            </div>
          </div>
<!--          <div class="cell addr text-weight-bold">当前值</div>-->
        </div>
        <div class="scrollbar scroll flex-1 list-bor">
          <template v-for="(item, index) in tableData">
            <div :key="index" class="flex items-center">
              <q-checkbox v-model="selData" :val="item.plcPointId" :disable="checkDisable(item)"/>
<!--              <q-radio v-model="selData" :val="item.plcPointId" />-->
              <div class="cell repName ellipsis">{{item.repName}}<q-tooltip>{{item.repName}}</q-tooltip></div>
<!--              <div class="cell addr ellipsis">{{item.addr}}<q-tooltip>{{item.addr}}</q-tooltip></div>-->
            </div>
            <div class="bor" :key="`bor_${item.plcPointId}`"/>
          </template>
        </div>
      </div>
      <div class="flex column" style="width: calc(100% - 340px);max-height: 100%">
        <div class="flex items-center header justify-between">
          <div class="cell repName text-weight-bold">历史曲线
            <div class="cursor-pointer margin-l-10 inline-block" style="font-weight: normal">
              <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" style="margin-top: -3px"/>
              <q-tooltip max-width="300px">仅展示60天内的历史数据</q-tooltip>
            </div>
          </div>
          <div class="flex items-center header justify-end margin-r-20" style="width: 200px;min-width: 200px">
            <div>
              <q-btn flat
                     color="primary"
                     :disable="!pointData.length || selPointData.dataType === 2 || selPointData.dataType === 9 || selData.length > 1"
                     @click="isTable = !isTable;pagination.pageNum = 1;getPlcData(selData.length > 1)"
                     class="btn table-flat-btn"
              >
                切换为{{ isTable ? '图表' : '表格' }}
              </q-btn>
            </div>
            <div>
              <export-btn class="btn table-flat-btn"
                style="margin: 0"
                :disable="!pointData.length"
                isFlat
                :exportFun="exportFun"
                :exportParams="exportParams"
                :exportName="getExportName()"/>
            </div>
          </div>
        </div>
        <div class="scrollbar scroll flex-1 list-bor" ref="dataList">
          <yz-condition-filter
            class="margin-t-20 margin-b-20"
            v-model="queryParams"
            @resetSearch="resetSearch"
            @onSubmit="pagination.pageNum = 1;getPlcData(selData.length > 1)"
          >
            <div>
              <span>时间：</span>
              <date-picker
                format="YYYY-MM-DD HH:mm:ss"
                :editable="false"
                clearable
                v-model="queryParams.dateTime"
                type="datetime"
                range
                :show-time-panel="showTimeRangePanel"
                placeholder="选择时间范围"
                style="width: 320px"
              >
                <template v-slot:footer>
                  <div class="flex justify-between items-center">
                    <div>
                      <button class="mx-btn mx-btn-text" @click="setDateTime(3)">
                        最近3小时
                      </button>
                      <button class="mx-btn mx-btn-text" @click="setDateTime(8)">
                        最近8小时
                      </button>
                      <button class="mx-btn mx-btn-text" @click="setDateTime(24)">
                        最近24小时
                      </button>
                    </div>
                    <button class="mx-btn mx-btn-text" @click="showTimeRangePanel = !showTimeRangePanel">
                      {{ showTimeRangePanel ? '选择日期' : '选择时间' }}
                    </button>
                  </div>
                </template>
              </date-picker>
            </div>
          </yz-condition-filter>
          <div
            ref="chart"
            class="margin-b-20 margin-t-20"
            style="width: 100%; height: 500px; max-width: 100%"
            v-show="!isTable"
          />
          <div style="max-height: 100%" v-if="isTable">
            <q-table
              :data="pointData"
              :columns="columns"
              row-key="number"
              id="table"
              class="myTable"
              style="height: calc(100vh - 410px)"
              :pagination.sync="pagination"
              :hide-bottom="!!pointData.length"
              color="primary"
              :loading="isTableLoading"
            >
            </q-table>
            <yz-pagination v-model="pagination" @onSearch="getPlcData"/>
          </div>
        </div>
      </div>
    </div>
    <set-point ref="setPoint" @getList="getPointsList"/>
  </div>
</template>

<script>
import { getPointsList, getPlcDataList, exportPlcData, getCheckPlcDataList } from 'src/boot/status-monitor/machine'
import setPoint from './components/set-point'
import moment from 'moment'
import { addListener } from 'resize-detector'
import echarts from 'echarts'
import _ from 'lodash'
export default {
  name: 'history-data',
  components: {
    setPoint
  },
  // dateTime: [new Date(moment(new Date()).subtract(24, 'days').format('YYYY-MM-DD HH:mm:ss')), new Date()]
  data () {
    return {
      isTableLoading: false,
      exportFun: exportPlcData,
      showTimeRangePanel: false,
      exportParams: {
        monitorKeys: []
      },
      queryParams: {
        dateTime: [new Date(moment(new Date()).subtract(1, 'hours').format('YYYY-MM-DD HH:mm:ss')), new Date()]
      },
      selData: [],
      tableData: [], // 列表数据源
      columns: [
        { name: 'indexId', label: '序号', field: 'indexId', align: 'left' },
        { name: 'value', label: '值', field: 'value', align: 'left' },
        { name: 'timeStr', label: '时间', field: 'timeStr', align: 'left' }
      ],
      isTable: false,
      selPointData: {},
      pointData: [],
      chart: null, // 图表
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      }
    }
  },
  props: {
    processData: {
      type: Object,
      default: () => {}
    }
  },
  mounted () {
    addListener(this.$refs.dataList, this.$utils.debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100))
    if (this.processData.deviceId) {
      this.getPointsList()
    }
  },
  watch: {
    processData: {
      deep: true,
      handler: function (val) {
        if (val) {
          this.getPointsList()
        }
      }
    },
    selData: {
      deep: true,
      handler: function (val) {
        if (val) {
          if (val.length === 1) {
            const selData = this.tableData.find(item => item.plcPointId === val[0])
            this.selPointData = selData
            this.pagination.pageNum = 1
            // 数据类型为2的只可表格展示
            if (this.selPointData.dataType === 2 || this.selPointData.dataType === 9) {
              this.isTable = true
            }
            this.getPlcData()
          } else if (val.length > 5) {
            this.$message.warning('最多支持选择5个点位')
          } else if (val.length > 1 && val.length <= 5) {
            const plcPoint = _.keyBy(_.cloneDeep(this.tableData), 'plcPointId')
            const selPointData = plcPoint[val[0]]
            const repName = []
            val.forEach(item => {
              repName.push(plcPoint[item].repName)
            })
            selPointData.repName = repName
            this.selPointData = selPointData
            this.isTable = false
            this.getPlcData(true)
          }
        }
      }

    }
  },
  methods: {
    // 复选时禁用字符串类型(string9 和 char2)
    checkDisable (item) {
      let disable = false
      if (this.selData.length) {
        if (_.indexOf(this.selData, item.plcPointId) === -1) {
          // 字符串型点位被选中时其它类型点位不可选，其它点位被选中时，字符串类型点位不可选
          const dataType = Array.isArray(this.selPointData) ? this.selPointData[0].dataType : this.selPointData.dataType
          disable = item.dataType + '' === '2' || item.dataType + '' === '9' || dataType + '' === '2' || dataType + '' === '9'
          // console.log(dataType, item.dataType, item.repName, Array.isArray(this.selPointData))
        }
      }
      return disable
    },
    setDateTime (hour) {
      this.queryParams.dateTime = [new Date(moment(new Date()).subtract(hour, 'hours').format('YYYY-MM-DD HH:mm:ss')), new Date()]
    },
    resetSearch () {
      this.queryParams = {
        dateTime: [new Date(moment(new Date()).subtract(1, 'hours').format('YYYY-MM-DD HH:mm:ss')), new Date()]
      }
    },
    getPointsList () {
      getPointsList(this.processData.deviceId).then(res => {
        // res.data[2].dataType = 2

        this.tableData = res.data
        this.selData = this.tableData.length ? [this.tableData[0].plcPointId] : null
      })
    },
    setPoint () {
      this.$refs.setPoint.showDialog(this.processData.deviceId, this.tableData)
    },
    getExportName () {
      return `${_.join(this.exportParams.monitorKeys, '、')}.xls`
    },
    /**
     * 获取plc数据
     * @param isCheck 是否为复选
     */
    getPlcData (isCheck) {
      if (this.queryParams.dateTime[0] && this.queryParams.dateTime[1] && Math.abs(moment(this.queryParams.dateTime[0]).diff(moment(this.queryParams.dateTime[1]), 'days')) > 60) {
        this.$message.warning('时间范围不可超过60天')
        return
      }
      const params = {
        monitorKeys: isCheck ? this.selPointData.repName : [this.selPointData.repName],
        deviceId: this.processData.deviceId
      }
      this.queryParams.dateTime[0] && (params['startDate'] = moment(this.queryParams.dateTime[0]).format('YYYY-MM-DDTHH:mm:ss'))
      this.queryParams.dateTime[1] && (params['endDate'] = moment(this.queryParams.dateTime[1]).format('YYYY-MM-DDTHH:mm:ss'))
      this.exportParams = params
      this.isTable && (params['pageNum'] = this.pagination.pageNum)
      this.isTable && (params['pageSize'] = this.pagination.pageSize)
      !isCheck && this.getPlcDataList(params)
      isCheck && this.getCheckPlcDataList(params)
    },
    getCheckPlcDataList (params) {
      getCheckPlcDataList(params).then(res => {
        const xAxisData = []
        let dtos = []
        if (res) {
          res.xaxisList.forEach(item => {
            xAxisData.push(`${moment(item).format('MM-DD')}\n${moment(item).format('HH:mm:ss')}`)
          })
          dtos = res.dtos
        }
        this.pointData = dtos
        this.getChart(xAxisData, dtos, true)
      })
    },
    getPlcDataList (params) {
      getPlcDataList(params).then(res => {
        res.list.forEach((item, index) => {
          item.indexId = (this.pagination.pageNum - 1) * this.pagination.pageSize + index + 1
          item.timeStr = moment(item.time).format('YYYY-MM-DD HH:mm:ss')
          item.timeLabel = `${moment(item.time).format('MM-DD')}\n${moment(item.time).format('HH:mm:ss')}`
        })
        this.pointData = res.list
        this.selPointData.setMap = res.plcWarnSetMap[this.selPointData.repName]
        // console.log(res)
        this.pagination.rowsNumber = res.total
        const xAxisData = _.map(this.pointData, 'timeLabel')
        const data = _.map(this.pointData, 'value')
        !this.isTable && this.getChart(xAxisData, [{ label: this.selPointData.repName, values: data }])
      })
    },
    getMarkLineData () {
      let markLineData = {}
      if (this.selPointData.setMap && !_.isNil(this.selPointData.setMap.constLogicMap)) {
        const setMap = this.selPointData.setMap.constLogicMap
        const nameList = Object.keys(setMap)
        if (nameList.length) {
          markLineData = []
          nameList.forEach(item => {
            markLineData.push({
              name: `${item}${setMap[item]}`,
              yAxis: setMap[item]
            })
          })
        }
      }
      return markLineData
    },
    getChart (xAxisData, data, isCheck) {
      const series = this.getSeries(data, isCheck)
      this.chart = echarts.init(this.$refs.chart)
      const legendData = _.map(data, 'label')

      console.log(legendData)
      // console.log(markLine)
      const option = {
        grid: {
          top: 35,
          bottom: 90,
          left: 60,
          right: 60
        },
        tooltip: {
          trigger: 'axis'
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 60,
            end: 100
          },
          {
            type: 'inside',
            realtime: true,
            start: 60,
            end: 100
          }
        ],
        legend: {
          data: legendData,
          right: 10
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          }
        },
        series: series
      }
      // 基于准备好的dom，初始化echarts实例
      if (this.chart) {
        this.chart.clear()
        this.chart.setOption(option)
      } else {
        this.$nextTick(() => {
          this.chart = echarts.init(this.$refs.chart)
          this.chart.setOption(option)
        })
      }
    },
    getSeries (data, isCheck) {
      const colorList = ['#5F77FD', '#18d77f', '#f7b82d', '#af23cc', '#38def4']
      const series = []
      data.forEach((item, index) => {
        const line = {
          name: item.label,
          type: 'line',
          step: 'end',
          lineStyle: {
            normal: {
              width: 2,
              color: colorList[index]
            }
          },
          symbolSize: 8,
          itemStyle: {
            normal: {
              color: colorList[index],
              borderWidth: 2,
              borderColor: colorList[index]
            },
            emphasis: {
              color: colorList[index],
              borderColor: colorList[index]
            }
          },
          data: item.values
        }
        series.push(line)
      })
      // 复选不显示阈值范围
      if (!isCheck) {
        const markLineData = this.getMarkLineData()
        series[0].markLine = {
          data: markLineData,
          lineStyle: {
            normal: {
              width: 2,
              color: '#18d77f'
            }
          },
          label: {
            formatter: (params) => {
              return params.name
            }
          }
        }
      }
      return series
    }
  }
}
</script>

<style scoped lang="stylus">
  >>>.q-checkbox__bg{
    border-radius 50% !important
  }
  >>>.q-checkbox__check.fit{
    width: calc(100% - 8px) !important;
    height: calc(100% - 8px) !important;
    top: 4px;
    left: 4px;
  }
  //>>>.q-table td:first-child{
  //  padding-left 10px !important
  //  padding-right 0 !important
  //}
  .header{
    height: 40px;
    line-height: 40px;
    width: 100%;
    background: #F3F3F3;
    //border-bottom: 1px solid #D3D3D3;
    border-radius: 6px 6px 0px 0px;
  }
  .list-bor{
    border: 1px solid #F3F3F3;
    border-top 0
    border-radius: 0px 0px 6px 6px;
    .bor{
      height 1px
      background-color #D3D3D3
      margin 0 10px
    }
  }
  .cell{
    padding 0 10px
    &.repName{
      width 260px
    }
  }
</style>
